import storage from "store";
import { axios } from "@/request";
import router from "@/router";
import baseLayout from "@/layout/baseLayout";
import demo from "@/views/demo/tree/index";
import { SET_AUTHINFO, LS_AUTH_INFO, SET_ASSETS } from "../mutation-types";

let AUTH_INFO = storage.get(LS_AUTH_INFO) || {
  token: "",
  userInfo: {}
};

function filterAsyncRouter(routes) {
  if (!routes.length) return;
  routes.forEach(item => {
    console.log(() => import(`@/views/demo/tree/index`));
    item.address && (item.component = () => import(`@/views${item.address}`)); // 此处有个坑后端组件字段最好不用component
    if (item.children && item.children.length) {
      item.component = baseLayout; // 如果有children则视为容器
      item.redirect = { name: item.children[0].name }; // 重定向到下一级
      filterAsyncRouter(item.children);
    }
  });
}

export default {
  state: {
    authInfo: AUTH_INFO, // 当前用户登录信息
    assets: {} // 菜单角色等信息
  },
  mutations: {
    [SET_AUTHINFO](state, authInfo) {
      state.authInfo.token = authInfo.jwt;
      state.authInfo.userInfo = authInfo.user;
      storage.set(LS_AUTH_INFO, state.authInfo, 7 * 24 * 60 * 60 * 1000);
    },
    [SET_ASSETS](state, assets) {
      state.assets = assets;
    }
  },
  actions: {
    // 登录
    async login({ commit }, userAuth) {
      await commit(SET_AUTHINFO, userAuth); // 保存登录信息
    },
    // 获取菜单
    async getMenus({ commit, rootState }) {
      const layout = rootState.app.defaultSettings.layout;
      const defaultLayout = require(`@/layout/${layout}/index`); // 选择布局
      let baseRoutes = [
        {
          path: "/",
          name: "Index",
          component: defaultLayout.default,
          children: []
        },
        {
          path: "*",
          redirect: "/404"
        }
      ];
      let res = await axios.get("/menu/getMenuInfoByUsernameAndAppId");
      if (res.code == 0) {
        commit(SET_ASSETS, res.data);
        // 动态添加路由
        const routes = JSON.parse(JSON.stringify(res.data.permissions.menus));
        filterAsyncRouter(routes);
        baseRoutes[0].children = routes; //将路由动态加入
        baseRoutes[0].redirect = { name: baseRoutes[0].children.length && baseRoutes[0].children[0].name }; // 重定向
        router.addRoutes(baseRoutes);
      } else {
        this.$message.error(res.msg || "获取菜单失败");
      }
    }
  }
};
